import { AnyAction } from "redux";
import * as TYPES from "../action-types";
import LOGIN_TYPES from "src/typings/login-types";

export interface ProfileState {
  loginState: LOGIN_TYPES; //当前用户的登录状态
  user: any; //当前已经登录的用户信息
  error: string | null; //错误信息
}

let initStore: ProfileState = {
  //初始状态
  loginState: LOGIN_TYPES.UN_VALIDATE, //当前用户的登录状态
  user: null, //当前已经登录的用户信息
  error: null, //错误信息
};

export default function mineReducer(
  state: ProfileState = initStore,
  action: AnyAction
): ProfileState {
  switch (action.type) {
    case TYPES.VALIDATE:
      if (action.payload.success) {
        return {
          ...state,
          loginState: LOGIN_TYPES.LOGINED,
          user: action.payload.data,
          error: null,
        };
      } else {
        return {
          ...state,
          loginState: LOGIN_TYPES.UNLOGIN,
          user: null, //用户名为空
          error: action.payload, //错误对象赋值
        };
      }
    case TYPES.LOGOUT:
      return {
        ...state,
        loginState: LOGIN_TYPES.UN_VALIDATE,
        user: null,
        error: null,
      };
    case TYPES.CHANGE_AVATAR:
      return { ...state, user: { ...state.user, avatar: action.payload } };
    default:
      return state;
  }
}
